<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="queryForm" class="query-form">
        <el-form-item label="综合查询">
          <el-input v-model.trim="queryForm.keywords" style="width: 180px;" clearable placeholder="请输入关键字" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="list" border stripe style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" min-width="180" show-overflow-tooltip />
        <el-table-column prop="code" label="角色编码" min-width="180" show-overflow-tooltip />
        <el-table-column prop="dataScope" label="数据权限" min-width="180">
          <template #default="scope">
            <span v-if="scope.row.dataScope == 0">
              全部数据
            </span>
            <span v-else-if="scope.row.dataScope == 1">
              部门及子部门数据
            </span>
            <span v-else-if="scope.row.dataScope == 2">
              本部门数据
            </span>
            <span v-else-if="scope.row.dataScope == 3">
              本人数据
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="角色描述" min-width="180" show-overflow-tooltip />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status == 1 ? 'success' : 'danger'">
              {{ scope.row.status == 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ $formatTimestamp(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="height: 18px;"></div>

      <el-pagination v-model:current-page="queryForm.pageNum" v-model:page-size="queryForm.pageSize"
        :page-sizes="[10, 50, 100, 500, 1000]" :total="total" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" destroy-on-close>
      <el-form ref="formRef" :model="roleForm" :rules="roleRules" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model.trim="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model.trim="roleForm.code" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="数据权限" prop="dataScope">
          <el-select v-model="roleForm.dataScope" placeholder="请选择数据权限">
            <el-option label="全部数据" :value="0" />
            <el-option label="部门及子部门数据" :value="1" />
            <el-option label="本部门数据" :value="2" />
            <el-option label="本人数据" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model.trim="roleForm.description" type="textarea" placeholder="请输入角色描述" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model.trim="roleForm.sort" :min="0" placeholder="排序（越大越靠前）" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="roleForm.status" placeholder="请选择状态">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { apiRoleList, apiRoleAdd, apiRoleUpdate, apiRoleDelete } from '@/api/system/role'

// 查询表单
const queryForm = ref<Record<string, any>>({
  pageNum: 1,
  pageSize: 10
})

// 列表与分页
const list = ref<any[]>([])
const total = ref(0)

// 获取列表
const fetchList = async () => {
  const res = await apiRoleList(queryForm.value)
  list.value = res.data?.records || []
  total.value = res.data?.totalRow || 0
}

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 角色表单
const initRoleForm = ref<Record<string, any>>({
  sort: 0,
  status: 1
})
const roleForm = ref<Record<string, any>>({ ...initRoleForm.value })

// 表单验证规则
const roleRules = {
  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
  dataScope: [{ required: true, message: '请选择数据权限', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
}

// 表单引用
const formRef = ref()

// 查询
const handleQuery = () => {
  queryForm.value.pageNum = 1
  fetchList()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增角色'
  isEdit.value = false
  // 重置表单
  Object.assign(roleForm.value = {}, initRoleForm.value)
  dialogVisible.value = true

}

// 编辑
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑角色'
  isEdit.value = true
  // 填充表单数据
  Object.assign(roleForm.value, row)
  dialogVisible.value = true
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除【${row.name}】吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await apiRoleDelete({ ids: String(row.id) })
    if (res.code == 200) {
      ElMessage.success('删除成功')
      handleQuery()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  })
}

// 提交表单
const submitForm = () => {
  formRef.value?.validate(async (valid: any) => {
    if (valid) {
      let res: any;
      if (isEdit.value) {
        res = await apiRoleUpdate(roleForm.value)
      } else {
        res = await apiRoleAdd(roleForm.value)
      }
      if (res.code === 200) {
        ElMessage.success('保存成功')
        dialogVisible.value = false
        handleQuery()
      } else {
        ElMessage.error(res.message || '保存失败')
      }
    }
  })
}

// 分页相关
const handleSizeChange = (val: number) => {
  queryForm.value.pageSize = val
  queryForm.value.pageNum = 1
  fetchList()
}

const handleCurrentChange = (val: number) => {
  queryForm.value.pageNum = val
  fetchList()
}

// 初始化
onMounted(() => {
  fetchList()
})
</script>

<style scoped>
.app-container {
  padding: 0px;
}

.query-form {
  margin-bottom: 0px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  text-align: right;
}
</style>